import Store from '@/redux/store';
import {Command} from '../constant';
import {Dispatch} from 'typings';
import {getActionProxy} from '@/redux/action-util';
import api from 'api';
import * as reduxStore from '@/redux/store';

import Action from './action';

import packageBRewardCenterMain from '../reducers/main';
import inviteCustomerRecordController from 'api/InviteCustomerRecordController';

export default (dispatch: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init() {
      await actions.loadReducer();

      const [customerInfo, customerBalance, distribute, inviteCustomer, messageContext] = await Promise.all([
        // 会员信息
        await api.customerBaseController.findCustomerCenterInfo(),
        // 会员余额信息
        await api.customerFundsController.statistics(),
        //分销设置信息
        await api.distributionController.getSettingAndInvitor(),
        //设置邀新人数
        await api.inviteCustomerRecordController.countInviteCustomer(),
        //消息中心
        await api.messageController.page({pageNum: 1, pageSize: 10}),
      ]);

      dispatch({
        type: Command.init,
        payload: {
          main: {
            isReady: true,
            customerInfo,
            customerBalance,
            inviteCustomer,
            noticeNum: messageContext.noticeNum,
            distribute: {
              //分销设置信息
              distributeSetting: distribute.distributionSettingSimVO,
              //邀请人信息
              inviteInfo: distribute.distributionCustomerSimVO,
            },
          },
        },
      });
    },
    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({type: Command.clean});
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageBRewardCenterMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageBRewardCenterMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return {actions};
};

//create by moon https://github.com/creasy2010/moon
